import React, {useState, useMemo, useEffect} from 'react';
import {Text, View, ScrollView, StyleSheet} from 'react-native';
import {connect, ConnectedProps} from 'react-redux';
import _ from 'lodash';
import {DragSortableView} from 'react-native-drag-sort'; //拖拽组件第三方库
import {RootState} from '@/models/index';
import {ICategory} from './../../models/category';
import Item, {parentWidth, itemWidth, itemHeight, itemMargin} from './Item';
import {RootStackNavigation} from '@/navigator/index';
import HeaderRightBtn from './HeaderRightBtn';
import Touchable from './../../components/Touchable';

const mapStateToProps = ({category}: RootState) => {
  return {
    categorys: category.categorys,
    myCategorys: category.myCategorys,
    isEdit: category.isEdit,
  };
};

const connector = connect(mapStateToProps);

type ModelState = ConnectedProps<typeof connector>;

interface IProps extends ModelState {
  navigation: RootStackNavigation;
}

// interface IState {
//   myCategorys: ICategory[];
//   categorys: ICategory[];
// }

const Category: React.FC<IProps> = props => {
  const {categorys, navigation, isEdit, dispatch} = props;
  const [myCategorys, setMyCategorys] = useState(props.myCategorys);
  const fixedItems = [0, 1];

  const toggleBtnStatus = () => {
    dispatch({
      type: 'category/toggle',
      payload: {
        myCategorys,
      },
    });
    if (isEdit) {
      navigation.goBack();
    }
  };
  navigation.setOptions({
    headerRight: () => (
      <HeaderRightBtn
        title={isEdit ? '完成' : '编辑'}
        onSubmit={toggleBtnStatus}
      />
    ),
  });
  const onLongPress = () => {
    dispatch({
      type: 'category/toggle',
      payload: {
        isEdit: true,
      },
    });
  };
  /**
   * 用于分类中的按钮点击事件  添加与删除我的分类
   * @param item 每一项数据
   * @param index 索引
   * @param selected 是否已经被选择我到我的
   */
  const onPress = (item: ICategory, index: number, selected: boolean) => {
    const disabled = fixedItems.indexOf(index) > -1;
    if (disabled) return;
    if (isEdit) {
      if (selected) {
        setMyCategorys(
          myCategorys.filter(selectedItem => item.id !== selectedItem.id),
        );
      } else {
        setMyCategorys(myCategorys.concat([item]));
      }
    }
  };
  /**
   * 我的中的各个分类按钮 renderUnSelectedItem同
   * @param item 每一项数据
   * @param index 索引
   * @returns 每一个小分类组件
   */
  const renderItem = (item: ICategory, index: number) => {
    const disabled = fixedItems.indexOf(index) > -1;
    return (
      // <Touchable
      //   key={item.id}
      //   onLongPress={onLongPress}
      //   onPress={() => onPress(item, index, true)}>
      <Item
        data={item}
        disabled={disabled}
        key={item.id}
        isEdit={isEdit}
        selected={true}
      />
      // </Touchable>
    );
  };
  // 下方分类中的按钮
  const renderUnSelectedItem = (item: ICategory, index: number) => {
    return (
      <Touchable
        key={item.id}
        onLongPress={onLongPress}
        onPress={() => onPress(item, index, false)}>
        <Item data={item} isEdit={isEdit} selected={false} />
      </Touchable>
    );
  };
  // 将数据从一个数组根据classify进行分割变成一个对象key为分类名
  const classifyGroup = useMemo(() => {
    // const classifyCategory: {[item: string]: ICategory[]} = {};
    // categorys.forEach(item => {
    //   let classify = item.classify || '';
    //   let classifyName = classifyCategory[classify];
    //   if (!classifyName) {
    //     classifyCategory[classify] = [];
    //   }
    //   classifyCategory[classify].push(item);
    // });
    // let classifyGroup =
    return _.groupBy(categorys, item => item.classify);
  }, [categorys]);
  useEffect(() => {
    return () => {
      dispatch({
        type: 'category/toggle',
        payload: {
          isEdit: false,
        },
      });
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
  /**
   *
   * @param data 拖拽组件会进行自动排序   这是经过拖拽之后排序过的数据
   */
  const onDataChange = (data: ICategory[]) => {
    setMyCategorys(data);
  };
  const onClickItem = (data: ICategory[], item: ICategory) => {
    onPress(item, data.indexOf(item), true);
  };
  return (
    <ScrollView style={styles.container}>
      <Text style={styles.classifyName}>我的分类</Text>
      <View style={styles.calssifyView}>
        {/* {myCategorys?.map(renderItem)} */}
        <DragSortableView
          //拖拽组件
          dataSource={myCategorys} //数据
          renderItem={renderItem} //数据的渲染 数据渲染时不可以用TouchAble之列包裹  否则无法进行拖拽
          fixedItems={fixedItems}
          sortable={isEdit} //是否可以拖拽
          keyExtractor={item => item.id} //指定当前key
          onDataChange={onDataChange} // 拖拽之后的回调
          parentWidth={parentWidth} //整体宽度
          childrenHeight={itemHeight} //每一个可拖拽元素的高度
          childrenWidth={itemWidth} // 每一个可拖拽元素的宽度
          marginChildrenTop={itemMargin} //每一个可拖拽元素marginTop
          onClickItem={(data, item) => {
            //点击事件  每一个拖拽元素  data为所有数据  item为点击元素的的数据
            onClickItem(data, item);
          }}
        />
      </View>
      <View>
        {Object.keys(classifyGroup).map(item => (
          <View key={item}>
            <Text style={styles.classifyName}>{item}</Text>
            <View style={styles.calssifyView}>
              {classifyGroup[item]?.map((item, index) => {
                if (
                  myCategorys?.find(selectedItem => selectedItem.id === item.id)
                ) {
                  return null;
                }
                return renderUnSelectedItem(item, index);
              })}
            </View>
          </View>
        ))}
      </View>
    </ScrollView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f3f6f6',
  },
  classifyName: {
    fontSize: 16,
    marginTop: 14,
    marginBottom: 8,
    marginLeft: 10,
  },
  calssifyView: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    padding: 5,
  },
});

export default connector(Category);
